from flask import Blueprint, request, jsonify, url_for
import requests
from app.extensions import db
from flask import current_app
from app.models.user import User
from app.utils import JwtToken

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    code = data['code']

    if not code:
        return jsonify({'code': 400, 'msg': '缺少code参数'}), 400

    appid = current_app.config['WX_APPID']
    secret = current_app.config['WX_SECRET']

    url = 'https://api.weixin.qq.com/sns/jscode2session'
    params = {
        'appid': appid,
        'secret': secret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }

    try:
        resp = requests.get(url, params=params)
        wx_data = resp.json()

        # 可选: 检查是否成功返回openid
        if 'openid' not in wx_data:
            return jsonify({'code': 500, 'msg': '微信登录失败', 'data': wx_data}), 500

        openid = wx_data['openid']
        token = JwtToken.generate_token(openid)

        # 查询用户是否已存在
        user = User.get_user_by_openid(openid)
        if not user:
            # 创建新用户
            user = User(openid=openid)  # username 和 avatar_url 有默认值
            db.session.add(user)
            db.session.commit()

        return jsonify({'code': 200, 'msg': 'success', "data": {'token': token, 'nickname': user.username, 'avatar': url_for('static', filename=user.avatar_url, _external=True)}})
    except Exception as e:
        return jsonify({'code': 500, 'msg': f'接口异常: {str(e)}'}), 500
